//
//  RDeptTreePopView.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/2/6.
//

import Foundation
import UIKit
import JFPopup

protocol RDeptTreePopViewDelegate: AnyObject {
    func handleSelected(_ dept: DeptTreeModal?)
    func handleClose()
}

class RDeptTreePopView: UIView {
    let treeTable = BSDeptTreeTable()
    weak var delegate: RDeptTreePopViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: .zero)
        backgroundColor = .white
        setupUI()
        reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadData() {
        showToastActivity()
        API.getRDepttree { responseModel in
            DispatchQueue.main.async {
                self.treeTable.datas = responseModel.models ?? []
                self.hideToastActivity()
            }
        }
    }
    
    @objc func saveTapped() {
        if treeTable.selectDept != nil {
            delegate?.handleSelected(treeTable.selectDept)
        }
    }
    
    @objc func clearTapped() {
        delegate?.handleClose()
    }
    
    func setupUI() {
        let clearBtn = UIButton.createDefaultLarge("取消")
        clearBtn.addTarget(self, action: #selector(clearTapped), for: .touchUpInside)
        addSubview(clearBtn)
        clearBtn.snp.makeConstraints { make in
            make.left.equalTo(self.snp.left).offset(16)
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(-8)
            make.width.equalTo((ScreenWidth - 48) / 2)
            make.height.equalTo(50)
        }
        
        let saveBtn = UIButton.createPrimaryLarge("确认")
        saveBtn.addTarget(self, action: #selector(saveTapped), for: .touchUpInside)
        addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(clearBtn.snp.right).offset(16)
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(-8)
            make.right.equalTo(self.snp.right).offset(-16)
            make.height.equalTo(50)
        }
        
        addSubview(treeTable)
        treeTable.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.snp.top).offset(10)
            make.bottom.equalTo(saveBtn.snp.top)
        }
    }
}
